<?php
/**
 * Created by PhpStorm.
 * User: cy
 * Date: 2018/4/9
 * Time: 16:12
 */
namespace app\modules\content\controllers;

use app\libs\GetData;
use app\modules\content\models\Recommend;
use Yii;
use yii\data\Pagination;
use app\libs\ApiControl;
use app\modules\cn\models\ResourcesPhone;

class RecommendController extends ApiControl {
    public $enableCsrfValidation = false;

    /**
     * 列表
     * @Author: Ferre
     * @create: 2021/3/9 15:03
     * @return string
     */
    public function actionIndex()
    {
        $where      = "1=1";
        $id         = Yii::$app->request->get('id');
        if (!empty($id)) $where .= " and id=$id";
        $count      = Recommend::find()->select("id")->where($where)->count();
        $page       = new Pagination(['totalCount'=>$count,'pageSize'=>20]);
        $recommend = Recommend::find()->asArray()->where($where)->offset($page->offset)->orderBy('id desc')->limit($page->limit)->all();
        return $this->render('index',['content'=>$recommend,'page'=>$page]);
    }

    // 修改和添加资讯，判断依据是$_POST['id']是否提交
    public function actionAdd()
    {
        if (!$_POST) {
            $id = Yii::$app->request->get('id', '');
            if (empty($id)) {
                return $this->render('add');
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%recommend}} where id=" . $id)->queryOne();
                return $this->render('add', ['data' => $data]);
            }
        } else {
            $getdata = new GetData();
            $must = array('name' => '标题', 'url' => '链接','type'=>'网站类型');
            $data = $getdata->PostData($must, 'recommend');
            $arr = $getdata->Auto('createTime');
            $data = array_merge($data, $arr);
            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%recommend}}", $data)->execute();
            } else {
                $info = new Recommend();
                $re = $info->updateAll($data, 'id=:id', array(':id' => $data['id']));
            }
            if ($re) {
                $this->redirect('index');
            } else {
                echo '<script>alert("数据添加/修改失败，请重试");history.go(-1);</script>';
                die;
            }

        }

    }

}
